import { Button, Input, message } from "antd";
import socket from "@/utils/socket";
import { useWebRTC } from "@/hooks/useWebRTC";
import { useSocketEvents } from "@/hooks/useSocketEvents";
import { VideoPlayer } from "@/components/VideoPlayer";

const Home = () => {
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [remoteStreams, setRemoteStreams] = useState<Map<string, MediaStream>>(new Map());
  const [roomId, setRoomId] = useState<string>("");
  const [inputRoomId, setInputRoomId] = useState<string>("");
  const [isHost, setIsHost] = useState(false);
  
  const { peerConnections, setPeerConnections, initPeerConnection } = useWebRTC(socket);

  const { cleanup } = useSocketEvents({
    socket,
    peerConnections,
    initPeerConnection,
    setRemoteStreams,
    remoteStreams,
    setPeerConnections,
    stream,
    roomId,
  });

  // 创建房间并开始共享
  const createRoom = async () => {
    socket.emit('create-room', async (newRoomId: string) => {
      setRoomId(newRoomId);
      setIsHost(true);
      message.success(`房间创建成功，房间号：${newRoomId}`);
      
      try {
        const mediaStream = await navigator.mediaDevices.getDisplayMedia({
          video: true,
        });

        mediaStream.getVideoTracks()[0].onended = () => {
          socket.emit("share-ended", newRoomId);
          setStream(null);
          cleanup();
          setRoomId("");
          setIsHost(false);
        };

        setStream(mediaStream);
      } catch (err) {
        console.error("获取屏幕共享失败:", err);
        message.error("获取屏幕共享失败");
      }
    });
  };

  // 加入房间
  const joinRoom = () => {
    if (!inputRoomId) {
      message.error("请输入房间号");
      return;
    }

    socket.emit('join-room', { roomId: inputRoomId }, (response: any) => {
      if (response.success) {
        setRoomId(inputRoomId);
        message.success("成功加入房间");
        
        cleanup();
      } else {
        message.error(response.message || "加入房间失败");
      }
    });
  };

  // 离开房间
  const leaveRoom = () => {
    cleanup();
    socket.emit('leave-room', roomId);
    setRoomId("");
    setIsHost(false);
    setStream(null);
    message.success("已离开房间");
  };

  return (
    <div className="p-4">
      {!roomId && (
        <div className="space-y-4">
          <div>
            <Button onClick={createRoom}>创建房间并共享屏幕</Button>
          </div>
          <div className="flex gap-2">
            <Input 
              placeholder="输入房间号"
              value={inputRoomId}
              onChange={(e) => setInputRoomId(e.target.value)}
            />
            <Button onClick={joinRoom}>加入房间</Button>
          </div>
        </div>
      )}

      {roomId && (
        <div className="mb-4">
          <div className="flex justify-between items-center">
            <div>
              <h2>房间号: {roomId}</h2>
              {isHost && <p>你是房主</p>}
            </div>
            <Button onClick={leaveRoom}>离开房间</Button>
          </div>
        </div>
      )}
      
      {stream && (
        <div className="mb-4">
          <h3>我的共享</h3>
          <VideoPlayer stream={stream} userId={socket.id} />
        </div>
      )}
      
      {remoteStreams.size > 0 && (
        <div>
          <h3>房主的共享</h3>
          <div className="grid grid-cols-1 gap-4">
            {Array.from(remoteStreams).map(([userId, stream]) => (
              <VideoPlayer key={userId} stream={stream} userId={userId} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default Home;
